package com.itheima.controller;


import com.itheima.common.R;
import com.itheima.dto.AddAddressDto;
import com.itheima.dto.SetDefaultDto;
import com.itheima.dto.UpdateAddressDto;
import com.itheima.pojo.AddressBook;
import com.itheima.service.AddressBookService;
import com.itheima.vo.GetDefaultsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("addressBook")
public class AddressBookController {


    @Resource
    private AddressBookService addressBookService;

    /**
     * 添加收货地址
     */
    @PostMapping("")
    public AddressBook addAddressBook(@RequestBody AddAddressDto dto){

        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(dto,addressBook);

        return addressBookService.save(addressBook);
    }

    /**
     * 根据id获取收获地址
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<AddressBook> getAddressById(@PathVariable(value = "id") String id) {

        return R.success(addressBookService.getAddressById(id));

    }


    /**
     * 获取收获地址列表
     *
     * @return
     */
    @GetMapping("list")
    public R<List<AddressBook>> getAddressList() {

        List<AddressBook> addressList = addressBookService.getAddressList();


        return R.success(addressList);
    }

    /**
     * 修改收获地址
     *
     * @param dto
     * @return
     */
    @PutMapping("")
    public R<String> updateAddress(@RequestBody UpdateAddressDto dto) {
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(dto, addressBook);

        Boolean res = addressBookService.updateAddress(addressBook);

        return res ? R.success("修改成功") : R.error("修改失败");
    }

    /**
     * 设置默认收货地址
     *
     * @param dto
     * @return
     */
    @PutMapping("default")
    public R<AddressBook> setDefault(@RequestBody SetDefaultDto dto) {

        AddressBook addressBook = addressBookService.updateDefault(dto.getId());

        return  R.success(addressBook);

    }

    /**
     *获取默认收获地址
     * @return
     */
    @GetMapping("default")
    public R<AddressBook> getDefault() {

        AddressBook addressBook = addressBookService.getDefaultAddress();
        return R.success(addressBook);

    }

    /**
     * 删除收货地址
     * @param ids
     * @return
     */
    @DeleteMapping("")
    public R<String> removeAddress(String ids){

        Boolean res = addressBookService.delete(ids);

        return R.success("删除成功");

    }


}
